﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    DBConnection connect = new DBConnection();
    static DataTable tbGioHang = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    { 
        
        if (!IsPostBack)
        {
            if (Session["GioHang"] != null)
            {
                tbGioHang = Session["GioHang"] as DataTable;
            }
            else
            {
                tbGioHang.Rows.Clear();
                tbGioHang.Columns.Clear();
                tbGioHang.Columns.Add("idSP", typeof(int));
                tbGioHang.Columns.Add("TenSP", typeof(string));
                tbGioHang.Columns.Add("Gia", typeof(float));
                tbGioHang.Columns.Add("SoLuong", typeof(int));
                tbGioHang.Columns.Add("TongTien", typeof(float), "SoLuong * Gia");
            }

            String ProductId = Request.QueryString["ProductID"].ToString();

            int id1 = Convert.ToInt32(ProductId);
            GetProductDetail(id1);
            
        }
    }

 
    private void GetProductDetail(int id)
    {
        DataList1.DataSource = connect.GetProductById(id);
        DataList1.DataBind();
        DataList2.DataSource = connect.GetProductDetail(id);
        DataList2.DataBind();

    }
    protected void button(object sender, EventArgs e)
    {

    }
    protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
    {
   
    }
    
    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        
        if (e.CommandName == "themvaogio")
        { 
            if (Session["account"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {

                int IdSP = int.Parse(((Label)e.Item.FindControl("lblIdSP")).Text);
                string TenSP = ((Label)e.Item.FindControl("LblName")).Text;
                float GiaSP = float.Parse(((Label)e.Item.FindControl("lbtPrice")).Text);
                int SoLuong = 1;

                Boolean b = true;
                foreach (DataRow row in tbGioHang.Rows)
                {
                    if ((int)row["idSP"] == IdSP)
                    {
                        row["SoLuong"] = (int)row["SoLuong"] + 1;
                        b = false;
                        break;
                    }
                }
                if (b)
                {
                    tbGioHang.Rows.Add(IdSP, TenSP, GiaSP, SoLuong);

                }
                Session["GioHang"] = tbGioHang;

                Response.Write("<script>alert('Đã thêm vào giỏ hàng ^.*!...')</script>");
                Response.Redirect("index.aspx");
            }

        }
    }
}